package com.nami.ucenter.domain.service;


import com.nami.gate.external.basic.constants.DownTopicConst;
import com.nami.ucenter.domain.port.publisher.DomainEventPublisher;
import com.nami.ucenter.domain.model.LogoutModel;
import com.nami.ucenter.domain.port.repository.CacheUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.SessionUtil;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceLogoutDomainService {

    private final DomainEventPublisher eventPublisher;
    private final CacheUserRepository cacheUserDomainService;

    public boolean terminateUserSession(String appKey, String userId, String instanceId) {
        return cacheUserDomainService.removeOnlDevice(appKey, userId, instanceId);
    }

    public boolean validateLogoutModelParams(LogoutModel logoutModel) {
        if (StringUtils.isBlank(logoutModel.getUserId())) {
            return Boolean.FALSE;
        }
        if (StringUtils.isBlank(logoutModel.getInstanceId())) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    public void fillLogoutParams(LogoutModel logoutModel) {
        String mqTags = cacheUserDomainService.getUserMqTags(logoutModel.getAppKey(),
            logoutModel.getUserId(), logoutModel.getInstanceId());
        logoutModel.setMqTags(mqTags);
    }

    public void publishLogoutEvent(LogoutModel logoutModel) {
        eventPublisher.publish(DownTopicConst.CLOSE_CHANNEL_TOPIC, logoutModel.getMqTags(),
            SessionUtil.binding(logoutModel.getUserId(), logoutModel.getInstanceId()));
    }
}
